import z from 'zod'
import { request } from '.'

// 密码登录
const LoginRequestShchema = z.object({
  grant_type: z.string(),
  password: z.string(),
  // 可以填写手机号或者邮箱，后端会自动识别
  username: z.string(),
})

const loginResponseSchema = z.object({
  '.expires': z.string(),
  '.issued': z.string(),
  'access_token': z.string(),
  'expires_in': z.number(),
  'token_type': z.string(),
})

export function login(data: z.infer<typeof LoginRequestShchema>) {
  return request({
    method: 'POST',
    url: '/oauth/login',
    data,
    dataValidator: LoginRequestShchema,
    responseValidator: z.object({
      entry: loginResponseSchema,
    }),
  })
}

// 验证码登录
const VerifyCodeLoginRequestSchema = z.object({
  phone: z.string(),
  verificationCode: z.string(),
})

export function verifyCodeLogin(data: z.infer<typeof VerifyCodeLoginRequestSchema>) {
  return request({
    method: 'POST',
    url: '/login/sms',
    data,
    dataValidator: VerifyCodeLoginRequestSchema,
    responseValidator: loginResponseSchema,
  })
}

// 注册
const RegisterRequestSchema = z.object({
  password: z.string(),
  data: z.string(),
  verificationCode: z.string(),
})

export function register(data: z.infer<typeof RegisterRequestSchema>) {
  return request({
    method: 'POST',
    url: '/api/auth/signup-with-credential',
    data,
    dataValidator: RegisterRequestSchema,
  })
}

// 发送验证码
const VerifyCodeRequestSchema = z.object({
  data: z.string(),
})

export function verifyCode(data: z.infer<typeof VerifyCodeRequestSchema>) {
  return request({
    method: 'POST',
    url: '/api/sms/send-verification-code',
    data,
    dataValidator: VerifyCodeRequestSchema,
  })
}

// 校验教师邀请码
const VerifyTeacherInviteCodeRequestSchema = z.object({
  code: z.string(),
  school: z.string(),
})

export function verifyTeacherInviteCode(data: z.infer<typeof VerifyTeacherInviteCodeRequestSchema>) {
  return request({
    method: 'POST',
    url: '/check-teacher-invitation-code',
    data,
    dataValidator: VerifyTeacherInviteCodeRequestSchema,
  })
}

// 修改/重置密码
const ResetPasswordRequestSchema = z.object({
  password: z.string(),
  phoneNumber: z.string(),
  verificationCode: z.string(),
})

export function resetPassword(data: z.infer<typeof ResetPasswordRequestSchema>) {
  return request({
    method: 'POST',
    url: '/api/auth/reset-password',
    data,
    dataValidator: ResetPasswordRequestSchema,
  })
}
